package com.android.support.lib.universal.sdk.weixin.base;

import java.io.ByteArrayOutputStream;

import com.android.support.lib.universal.sdk.weixin.wxapi.Constants;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.content.Context;
import android.graphics.Bitmap;

import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXTextObject;
import android.graphics.Bitmap.CompressFormat;
import android.widget.Toast;

/**
 * Created by 彭治铭 on 2016/5/4.
 * 微信分享
 */
public class WXShareEntry {
    private static String APP_ID = Constants.APP_ID;
    private static final int MIN_SUPPORTED_VERSION = 0x21020001;//图文分享，微信最低版本要求。

    Context context;
    IWXAPI api;
    //发送到微信的信息
    WXMediaMessage msg;

    public WXShareEntry(Context context) {
        super();
        this.context = context;
        api = WXAPIFactory.createWXAPI(context, APP_ID, true);
        api.registerApp(APP_ID);
        msg = new WXMediaMessage();
    }

    /**
     * 分享文本
     *
     * @param text 文本内容
     * @param bool true(分享到朋友圈)，false(会话)
     */
    public void sendText(String text, Boolean bool) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context,
                    "请先安装微信",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        WXTextObject textObj = new WXTextObject();
        textObj.text = text;
        // 用WXTextObject对象初始化一个WXMediaMessage对象
        msg.mediaObject = textObj;
        // 发送文本类型的消息时，title字段不起作用
        // msg.title = "Will be ignored";
        msg.description = text;

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis()); // transaction字段用于唯一标识一个请求
        req.message = msg;
        /**
         * WXSceneSession 分享到会话（默认） WXSceneTimeline 分享到朋友圈
         */
        if (bool) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        // 调用api接口发送数据到微信
        api.sendReq(req);
    }

    /**
     * 分享图片
     *
     * @param bitmap 位图
     * @param bool   true(分享到朋友圈)，false(会话)
     */
    public void sendImg(Bitmap bitmap, Boolean bool) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context,
                    "请先安装微信",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        WXImageObject imgObj = new WXImageObject(bitmap);
        msg.mediaObject = imgObj;
        // msg.mediaObject = imgObj;
        msg.mediaObject = imgObj;
        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis()); // transaction字段用于唯一标识一个请求
        req.message = msg;
        /**
         * WXSceneSession 分享到会话（默认） WXSceneTimeline 分享到朋友圈
         */
        if (bool) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        // 调用api接口发送数据到微信
        api.sendReq(req);
    }

    /**
     * 微信图文分享
     *
     * @param title  标题
     * @param url    点击图文后，所跳转的链接
     * @param bitmap 图片，大小不能超过1M,不然报错，无法分享成功。
     * @param bool   是否分享到朋友圈
     */
    public void shareToWXFriends(String title,
                                 String url, Bitmap bitmap, Boolean bool) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context,
                    "请先安装微信",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (api.getWXAppSupportAPI() < MIN_SUPPORTED_VERSION) {
            Toast.makeText(
                    context,
                    "当前微信版本较低，不支持图文分享，请升级到最新版本", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = url;
        msg.thumbData = bmpToByteArray(bitmap, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis()) + "";
        req.message = msg;
        if (bool) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        api.sendReq(req);
    }

    public static byte[] bmpToByteArray(final Bitmap bmp,
                                        final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
